const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

/**
 * 运行一个微队列任务
 * 把传递的函数放到微队列中
 * @param {*} callback 
 */
function runMicroTask(callback){
    // 判断node环境
    if (process&&process.nextTick) {
        process.nextTick(callback)
    }
    // 浏览器环境
    else if (MutationObserver) {
        const observer = new MutationObserver(callback)
    }
    // 低版本浏览器环境
    else {
        setTimeout(callback, 0);
    }
}

class MyPromise{
    /**
     * 创建一个promise
     */
    constructor(executor) {
        this._state = PENDING
        this._value = undefined
        this._handlers = [] // 处理函数形成的队列
        try {
            executor(this._resolve.bind(this), this._reject.bind(this))
        } catch (error) {
            this._reject(error)
        }
    }

    /**
     * 
     * @param {Function} executor 追加的函数
     * @param {String} state 该函数在什么状态下执行
     * @param {Function} resolve 让then函数返回的promise成功
     * @param {Function} reject 让then函数返回的promise失败
     */
    _pushHandler(executor, state, resolve, reject) {
        this._handlers.push({executor, state, resolve, reject})
    }
    
    /**
     * 执行then函数下的队列
     */
    _runHandlers() {
        if(this._state === PENDING) {
            // 目标任务仍在挂起
            return
        }
        console.log(`处理${this._handlers.length}`)
        console.log(this._handlers)
        while(this._handlers[0]){
            const handler = this._handlers[0]
            this._runOneHandler(handler)
            this._handlers.shift()
        }
    }

    /**
     * 处理一个then函数
     * @param {Object} handler 
     */
    _runOneHandler(handler) {
        runMicroTask(()=>{
            if (this._state !== handler.state ) {
                // 不作任何处理
                return
            }
            if (typeof handler.executor !== 'function') {
                // 传递后续处理并非一个函数
                this._state === FULFILLED
                    ? handler.resolve(this._value)
                    : handler.reject(this._value)
                return
            }
        })
    }

    /**
     * promise then函数
     * @param {Function} onFulfilled 
     * @param {Function} onRejected 
     */
    then(onFulfilled, onRejected) {
        return new MyPromise((resolve, reject)=>{
            this._pushHandler(onFulfilled, FULFILLED, resolve, reject)
            this._pushHandler(onRejected, REJECTED, resolve, reject)
            this._runHandlers()
        })
    }

    /**
     * 抽离改变状态的函数
     */
    _changeState(newState, value){
        if (this._state !== PENDING) {
            return
        }
        this._state = newState
        this._value = value
        this._runHandlers()
    }


    /**
     * 调用完成
     */
    _resolve(data) {
        this._changeState(FULFILLED, data)
    }

    /**
     * 调用失败
     */
    _reject(reason) {
        this._changeState(REJECTED, reason)
    }
}

// setTimeout(() => {
//     console.log("1", 1)
// }, 0);
// runMicroTask(()=>{
//     console.log("2", 2)
// })
// console.log("3", 3)


const pro = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(123)
    }, 0);
})
pro.then(function A1() {})
pro.then(function A2() {}, function B2() {})

console.log(pro)